from ipmininet.iptopo import IPTopo
from ipmininet.router.config import RouterConfig, Openr, SSHd
from ipmininet.ipnet import IPNet
from ipmininet.cli import IPCLI

HOSTS_PER_ROUTER = 1


class OpenrConfig(RouterConfig):
    """A simple config with only a OpenR daemon"""

    def __init__(self, node, *args, **kwargs):
        defaults = {"enable_v4": True, "ifname_prefix": "", "iface_regex_exclude": "l*"}
        defaults = {"enable_v4": True}
        super().__init__(node, daemons=((Openr, defaults),), *args, **kwargs)


class RocketfuelTopo(IPTopo):
    def build(self, *args, **kwargs):
        routers = []
        for line in open('1755.r0.cch'):
            arr = line.split()
            routers.append('r' + arr[0])
            self.addRouter('r' + arr[0], config=OpenrConfig,
                           privateDirs=['/tmp', '/var/log'])

        for line in open('1755.r0.cch'):
            arr = line.split('->')[1].split('=')
            nei_str = arr[0].replace(' ', '')
            nei_ids = nei_str[1:-1].split('><')
            src = line.split()[0]
            for nei in nei_ids:
                if src == nei:
                    continue
                if ('r' + nei, 'r' + src) not in self.links() and ('r' + src, 'r' + nei) not in self.links():
                    self.addLink('r' + src, 'r' + nei)

        # r1, r2, r3, r4 = self.addRouters('r1', 'r2', 'r3', 'r4', config=OpenrConfig,
        #                                  privateDirs=['/tmp', '/var/log'])
        # self.addLinks((r1, r2), (r2, r3), (r3, r4), (r4, r1))
        for r in routers:
            for i in range(HOSTS_PER_ROUTER):
                self.addLink(r, self.addHost('h%s%s' % (i, r)),
                             params2={'v4_width': 1})

        super().build(*args, **kwargs)


net = IPNet(topo=RocketfuelTopo(), max_v4_prefixlen=26)
try:
    net.start()
    IPCLI(net)
finally:
    net.stop()
